<template>
  <div class="pokemon-detail">
    <el-page-header @back="router.back()">
      <template #content>
        <span class="pokemon-title">
          #{{ pokemon?.id.toString().padStart(3, '0') }} {{ pokemon?.name }}
        </span>
      </template>
    </el-page-header>

    <el-skeleton :loading="!pokemon" animated>
      <template #template>
        <el-space direction="vertical" alignment="center" size="large">
          <el-skeleton-item variant="image" style="width: 200px; height: 200px" />
          <el-skeleton-item variant="text" style="width: 100px" />
        </el-space>
      </template>
      
      <template #default>
        <el-card v-if="pokemon" class="detail-card">
          <div class="pokemon-info-container">
            <!-- 左侧：图片和属性 -->
            <div class="pokemon-basic">
              <el-image
                :src="pokemon.sprite"
                :alt="pokemon.name"
                fit="contain"
                class="pokemon-image"
              />
              <div class="pokemon-types">
                <el-tag
                  v-for="type in pokemon.types"
                  :key="type"
                  :class="['type', type]"
                  effect="dark"
                >
                  {{ t(`pokedex.types.${type}`) }}
                </el-tag>
              </div>
            </div>

            <!-- 右侧：描述信息 -->
            <div class="pokemon-description">
              <h3>{{ t('pokedex.description.about') }}</h3>
              <p class="description-text">{{ pokemon.description }}</p>
              <el-descriptions :column="1" border class="pokemon-meta">
                <el-descriptions-item :label="t('pokedex.description.category')">
                  {{ pokemon.species }}
                </el-descriptions-item>
              </el-descriptions>
            </div>
          </div>

          <!-- 标签页部分 -->
          <el-tabs v-model="currentTab" class="detail-tabs">
            <!-- 种族值 -->
            <el-tab-pane :name="'stats'" :label="t('pokedex.tabs.stats')">
              <el-card class="stats-card">
                <template #header>
                  <div class="card-header">
                    <span>{{ t('pokedex.stats.baseStats') }}</span>
                  </div>
                </template>
                
                <div class="stats-grid">
                  <div v-for="(value, key) in pokemon.stats" :key="key" class="stat-item">
                    <span class="stat-label">{{ t(`pokedex.stats.${key}`) }}</span>
                    <el-progress
                      :percentage="(value / 255) * 100"
                      :color="getStatColor(value)"
                      :format="() => value"
                      :stroke-width="20"
                    />
                  </div>
                </div>
              </el-card>
            </el-tab-pane>

            <!-- 技能列表 -->
            <el-tab-pane :name="'moves'" :label="t('pokedex.tabs.moves')">
              <div class="moves-container">
                <el-table :data="pokemon.moves" stripe>
                  <el-table-column
                    prop="name"
                    :label="t('pokedex.moves.name')"
                  />
                  <el-table-column
                    prop="power"
                    :label="t('pokedex.moves.power')"
                    width="100"
                  />
                  <el-table-column
                    prop="accuracy"
                    :label="t('pokedex.moves.accuracy')"
                    width="100"
                  />
                  <el-table-column
                    prop="type"
                    :label="t('pokedex.moves.type')"
                    width="120"
                  >
                    <template #default="{ row }">
                      <el-tag
                        :class="['type', row.type]"
                        effect="dark"
                      >
                        {{ t(`pokedex.types.${row.type}`) }}
                      </el-tag>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </el-tab-pane>

            <!-- 进化链 -->
            <el-tab-pane :name="'evolution'" :label="t('pokedex.tabs.evolution')">
              <el-card class="evolution-card">
                <el-space 
                  class="evolution-chain" 
                  alignment="center" 
                  :size="40"
                >
                  <template v-for="(stage, index) in evolutionChain" :key="index">
                    <div class="evolution-stage">
                      <el-image
                        :src="stage.sprite"
                        :alt="stage.name"
                        fit="contain"
                        style="width: 120px; height: 120px"
                      />
                      <el-text>{{ stage.name }}</el-text>
                    </div>
                    <el-icon v-if="index < evolutionChain.length - 1">
                      <ArrowRight />
                    </el-icon>
                  </template>
                </el-space>
              </el-card>
            </el-tab-pane>
          </el-tabs>
        </el-card>
      </template>
    </el-skeleton>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { ArrowRight } from '@element-plus/icons-vue'

const route = useRoute()
const router = useRouter()
const { t, locale: currentLocale } = useI18n()
const pokemon = ref<any>(null)
const evolutionChain = ref<any[]>([])

const currentTab = ref('stats')

const statLabels = {
  hp: 'HP',
  attack: '攻击',
  defense: '防御',
  'special-attack': '特攻',
  'special-defense': '特防',
  speed: '速度'
}

const fetchPokemonDetail = async () => {
  try {
    const id = route.params.id
    const response = await fetch(`https://pokeapi.co/api/v2/pokemon/${id}`)
    const data = await response.json()
    
    // 获取宝可梦的种类信息和描述
    const speciesResponse = await fetch(data.species.url)
    const speciesData = await speciesResponse.json()
    
    // 获取中文或英文描述
    const flavorText = speciesData.flavor_text_entries.find(
      (entry: any) => entry.language.name === (currentLocale.value === 'cn' ? 'zh-Hans' : 'en')
    )?.flavor_text.replace(/\f/g, ' ') || ''

    pokemon.value = {
      id: data.id,
      name: data.name,
      sprite: data.sprites.front_default,
      types: data.types.map((t: any) => t.type.name),
      stats: Object.fromEntries(
        data.stats.map((s: any) => [s.stat.name, s.base_stat])
      ),
      species: speciesData.genera.find((g: any) => g.language.name === 'en')?.genus || '',
      description: flavorText,
      moves: data.moves.map((m: any) => ({
        name: m.move.name,
      }))
    }

    // 获取进化链信息
    const evolutionResponse = await fetch(speciesData.evolution_chain.url)
    const evolutionData = await evolutionResponse.json()
    
    // 处理进化链数据
    await processEvolutionChain(evolutionData.chain)
  } catch (error) {
    console.error('Error fetching pokemon details:', error)
  }
}

const processEvolutionChain = async (chain: any) => {
  const processStage = async (stage: any) => {
    const id = stage.species.url.split('/').slice(-2, -1)[0]
    const response = await fetch(`https://pokeapi.co/api/v2/pokemon/${id}`)
    const data = await response.json()
    
    return {
      name: stage.species.name,
      sprite: data.sprites.front_default
    }
  }

  const chain_array = []
  let current = chain
  
  while (current) {
    chain_array.push(await processStage(current))
    current = current.evolves_to[0]
  }
  
  evolutionChain.value = chain_array
}

const getStatColor = (value: number): string => {
  if (value >= 180) return '#ff4444'      // 极高 - 红色
  if (value >= 140) return '#ff8844'      // 很高 - 橙红
  if (value >= 110) return '#ffcc44'      // �� - 橙黄
  if (value >= 70) return '#44cc44'       // 中等 - 绿色
  if (value >= 40) return '#88cc44'       // 低 - 黄绿
  return '#cccc44'                        // 很低 - 黄��
}

onMounted(() => {
  fetchPokemonDetail()
})
</script>

<style scoped lang="scss">
.pokemon-detail {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.pokemon-info-container {
  display: flex;
  gap: 40px;
  margin-bottom: 30px;

  @media (max-width: 768px) {
    flex-direction: column;
    gap: 20px;
  }
}

.pokemon-basic {
  flex-shrink: 0;
  text-align: center;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16px;

  .pokemon-image {
    width: 200px;
    height: 200px;
  }
  
  .pokemon-types {
    display: flex;
    gap: 8px;
    justify-content: center;
  }
}

.pokemon-description {
  flex: 1;
  min-width: 0;

  h3 {
    margin: 0 0 16px;
    color: var(--el-text-color-primary);
  }

  .description-text {
    font-size: 1.1em;
    line-height: 1.6;
    margin-bottom: 20px;
    color: var(--el-text-color-regular);
    white-space: pre-line;  // 保持换行格式
  }

  .pokemon-meta {
    margin-top: 20px;
  }
}

.stats-section {
  margin-top: 24px;
}

.detail-card {
  margin-top: 20px;
}

.pokemon-title {
  font-size: 20px;
  text-transform: capitalize;
}

/* 基础信息样式 */
.basic-info {
  text-align: center;
  margin-bottom: 30px;
}

/* 标签页样式 */
.detail-tabs {
  margin-top: 20px;
}

/* 属性卡片样式 */
.stats-card {
  margin-bottom: 20px;
}

/* 进化链样式 */
.evolution-chain {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

.evolution-stage {
  text-align: center;
}

/* 类型标签样式 */
.type {
  margin: 0 4px;
}

/* 保留原有的类型颜色样式 */
.type.grass { background-color: #78c850 !important; }
.type.fire { background-color: #f08030 !important; }
.type.water { background-color: #6890f0 !important; }
.type.bug { background-color: #a8b820 !important; }
.type.normal { background-color: #a8a878 !important; }
.type.poison { background-color: #a040a0 !important; }
.type.electric { background-color: #f8d030 !important; }
.type.ground { background-color: #e0c068 !important; }
.type.fairy { background-color: #ee99ac !important; }
.type.fighting { background-color: #c03028 !important; }
.type.psychic { background-color: #f85888 !important; }
.type.rock { background-color: #b8a038 !important; }
.type.ghost { background-color: #705898 !important; }
.type.ice { background-color: #98d8d8 !important; }
.type.dragon { background-color: #7038f8 !important; }

.moves-container {
  max-height: 400px;  /* 设置最大高度 */
  overflow-y: auto;   /* 添加垂直滚动条 */
  
  /* 美化滚动条样式 */
  &::-webkit-scrollbar {
    width: 8px;
  }
  
  &::-webkit-scrollbar-track {
    background: var(--el-fill-color-lighter);
    border-radius: 4px;
  }
  
  &::-webkit-scrollbar-thumb {
    background: var(--el-border-color);
    border-radius: 4px;
    
    &:hover {
      background: var(--el-border-color-darker);
    }
  }
  
  /* 适配火狐浏览器的滚动条样式 */
  scrollbar-width: thin;
  scrollbar-color: var(--el-border-color) var(--el-fill-color-lighter);
}

/* 确保表格头部固定 */
:deep(.el-table) {
  --el-table-header-bg-color: var(--el-bg-color);
  
  .el-table__header-wrapper {
    position: sticky;
    top: 0;
    z-index: 1;
  }
}
</style> 